<template>
  <app-section :loading="pageLoading">
    <van-nav-bar :title="navTitle" @click-left="backRoute" left-arrow/>
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">

      <desform-view
        :mode="mode"
        :dataId="dataId"
        :height="pageHeight"
        :desformCode="formConfig.desformCode"
        @success="handleSuccess"
        @dialogChange="handleDialogChange">
      </desform-view>

    </van-pull-refresh>
  </app-section>
</template>

<script>
  import AppSection from '@/components/AppSection'
  import { getAction,postAction,getFileAccessHttpUrl } from '@/api'
  import debounce from 'lodash/debounce';
  import DesformView from '@/components/online/DesformView'

  export default {
    name: 'SelectUsers',
    components:{
      AppSection,DesformView
    },
    props:{
      mode:{
        type:String,
        default:'add',
        required:false
      }
    },
    data(){
      this.searchByKeyword = debounce(this.searchByKeyword, 1000);//消抖
      return {
        pageLoading:false,
        navTitle:'',
        pullLoading: false,

        dataId:null,
        formConfig: {},

        url:"/sys/user/appUserList",
        saveUrl: '/process/extActDesignFlowData/add',
        startProcess: "/process/extActProcess/startDesFormMutilProcess",
        saveAndSubmitFlowUrl: '/process/extActDesignFlowData/saveAndStartDesFormMutilProcess',
        queryFormDataById: '/desform/data/queryById',
        userList:[],
        selectedList:[],
        keyword:'',
        destination:'',
        flowCodePre:'desform_',
      }
    },
    computed:{
      pageHeight(){
        return null
      }
    },
    methods:{
      initForm(formConfig){
        this.navTitle = "表单【"+formConfig.desformName+"】发起申请";
        this.formConfig = {...formConfig}
        if(this.mode==='edit'){
          this.dataId = formConfig.dataId
        }
      },
      // 返回
      backRoute(){
        this.$emit("back")
      },

      handleSuccess(event){
        //保存表单后执行
        this.$dialog.confirm({
          title: '提示',
          message:"确认提交流程吗?"
        }).then(() => {
          if(this.mode==='add'){
            //新增 直接保存ext_designer数据和提交流程一起走
            const that = this;
            that.saveAndSubmitFlowData(event).then(()=>{
              that.$toast.success({
                message:'提交成功!',
                onClose:()=>{
                  that.$router.push({name:'apply'})
                }
              });
            })
          }else{
            //编辑 只需要提交流程
            this.startDesFormProcess(this.formConfig.dataId);
          }
        }).catch(() => {
          if(this.mode==='add'){
            this.saveFlowData(event).then(()=>{
              this.$emit("save")
            })
          }
        });
      },
      async startDesFormProcess (formDataId){
        //根据desformDataId查询数据对象
        let res =  await getAction(this.queryFormDataById, {id:formDataId});
        if(!res.success){
          this.$toast(res.message);
          return;
        }
        let desformCode = this.formConfig.desformCode;
        //var jsonData = JSON.stringify(res.result.desformDataJson);
        var jsonData = res.result.desformDataJson;
        var param = {
          flowCode:this.flowCodePre+desformCode,
          id:this.formConfig.designId,
          formUrl:"{{DOMAIN_URL}}/desform/detail/"+desformCode+"/${BPM_DES_DATA_ID}?token={{TOKEN}}",
          formUrlMobile:"{{DOMAIN_URL}}/desform/detail/"+desformCode+"/${BPM_DES_DATA_ID}?token={{TOKEN}}",
          jsonData:jsonData,
        };
        const that = this
        postAction(that.startProcess,param).then((res)=>{
          if(res.success){
            that.$toast.success({
              message:'提交成功!',
              onClose:()=>{
                that.$router.push({name:'apply'})
              }
            });
          }else{
            that.$toast(res.message);
          }
        });
      },

      getSaveParams(desformDataId){
        return {
          desformId: this.formConfig.id,
          desformCode: this.formConfig.desformCode,
          desformDataId: desformDataId,
          desformName: this.formConfig.desformName,
          processName: this.formConfig.procName,
          titleExp: this.formConfig.titleExp,
          flowCode: this.flowCodePre+this.formConfig.desformCode,
        };
      },
      saveFlowData(event){
        let params = this.getSaveParams(event.dataId)
        return new Promise((resolve,reject)=>{
          postAction(this.saveUrl,params).then(res => {
            console.log(res)
            if (!res.success) {
              reject();
            }else{
              resolve();
            }
          })
        });
      },
      saveAndSubmitFlowData(event){
        let params = this.getSaveParams(event.dataId)
        return new Promise((resolve,reject)=>{
          postAction(this.saveAndSubmitFlowUrl,params).then(res => {
            if (!res.success) {
              reject(res);
            }else{
              this.$toast(res.message);
              resolve(res);
            }
          })
        });
      },

      handleDialogChange(){
        console.log('chuangkou daxiao gaibian shijian yidongduan shenme doubugan!')
      },
      searchByKeyword(){
        this.onRefresh()
      },
      onRefresh() {
        this.pullLoading = true
        this.pageNo = 1
        let param = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          keyword:this.keyword
        }
        this.userList=[]
        getAction(this.url,param).then(res=>{
          console.log("onRefresh",res);
          this.pullLoading = false
          if(res.success){
            this.pageNo++
            let arr = res.result.records
            for(let item of arr){
              this.userList.push(item)
            }
          }
        })
      },
      onLoad(){
        this.listLoading = true;
        let param = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          keyword:this.keyword
        }
        getAction(this.url,param).then(res=>{
          this.listLoading = false;
          if(res.success){
            // this.$toast.success("加载完成");
            this.pageNo++
            let arr = res.result.records
            for(let item of arr){
              this.userList.push(item)
            }

            if(!arr || arr.length<this.pageSize){
              console.log("加载完成!")
              this.listFinished = true;
            }
            console.log("结果数据", this.userList)
          }else{
            this.error = true;
          }
        }).catch(e=>{
          console.log("请求错误",e)
          this.error = true;
        })
      },

      toggleChecked(index){
        this.$refs.userCheckBox[index].toggle();
      },
      clearAll(flag){
        /**
         * flag 状态值
         * 0 委托人
         * 1 下一步的操作人
         * 2 抄送人
         */
        this.destination = flag
        this.selectedList=[]

      },
      backUserfulData(){
        let arr = []
        for(let item of this.selectedList){
          let obj = {
            username:item.username,
            realname:item.realname
          }
          if(!item.avatar){
            obj.avatar = ''
          }else{
              obj.avatar = getFileAccessHttpUrl(item.avatar)
          }
          arr.push(obj)
        }
        return arr;

      }

    }
  }
</script>

<style scoped>


</style>